package com.treasure.hunt.api.subscribe

import com.blankj.utilcode.util.SPStaticUtils
import com.module.lemlin.mode.SubscribeListener
import com.module.lemlin.rxhttp.CustomException
import com.module.lemlin.rxhttp.HttpServiceData
import com.module.lemlin.rxhttp.code
import com.treasure.hunt.app.AppConstance
import com.treasure.hunt.entity.LoginUserInfoResponse
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import rxhttp.RxHttp
import rxhttp.toClass

fun <HttpData : HttpServiceData> subscribe(
    observable: Observable<HttpData>,
    subscribe: SubscribeListener<HttpData>
): Disposable {

    return Observable.just(SPStaticUtils.getString("token", "null"))
        .flatMap { token ->
            if (token == "null") {
                val deviceNum: String =
                    SPStaticUtils.getString(AppConstance.KEY_NAME_UUID_IMEI)
                val parentId: String =
                    SPStaticUtils.getString(AppConstance.KEY_NAME_PARENT_ID, ("0")) ?: "0"
                RxHttp.postForm("/api/user/device_number")
                    //.setAssemblyEnabled(false)
                    .add("device_number", deviceNum)
                    .add("parent_id", parentId)
                    .add("type", 0)
                    .asClass(LoginUserInfoResponse::class.java)
                    .map {
                        it.data.userinfo.token
                    }
            } else {
                Observable.just(token)
            }
        }
        .doOnNext {
            SPStaticUtils.put("token", it)
        }
        .flatMap {
            observable
        }
        .observeOn(AndroidSchedulers.mainThread())
        .doOnSubscribe {
            subscribe.onStart()
        }.doOnNext {
            if (it.code != 1) throw CustomException("${it.code}", it.msg)
        }.subscribe({
            subscribe.onSuccess(it)
        }, {
            subscribe.onFailure(it)
            if (it.code == 401) {
                SPStaticUtils.remove("token")
            }
        })

//    return observable.observeOn(AndroidSchedulers.mainThread())
//        .doOnSubscribe {
//            subscribe.onStart()
//        }.doOnNext {
//            if (it.code != 1) throw CustomException("${it.code}", it.msg)
//        }.subscribe({
//            subscribe.onSuccess(it)
//        }, {
//            if (it.code == 401) RxLifeScope().launch({
//                if (ActivityCompat.checkSelfPermission(
//                        BaseApplication.INSTANCE,
//                        Manifest.permission.READ_PHONE_STATE
//                    ) != PackageManager.PERMISSION_GRANTED
//                ) {
//                    subscribe.onFailure(CustomException("90000", "设备权限未打开"))
//                    return@launch
//                }
//                login(PhoneUtils.getDeviceId()).data.let { userInfo ->
//                    SPStaticUtils.put("token", userInfo.userinfo.token)
//                }
//                subscribe(observable, subscribe)
//            }, { error ->
//                subscribe.onFailure(error)
//            }) else {
//                subscribe.onFailure(it)
//            }
//        })
}

suspend fun login(deviceNumber: String, parentId: Int = 0, type: Int = 0): LoginUserInfoResponse =
    RxHttp.postForm("/api/user/device_number")
        //.setAssemblyEnabled(false)
        .add("device_number", deviceNumber)
        .add("parent_id", parentId)
        .add("type", type)
        .toClass<LoginUserInfoResponse>()
        .await()